package com.smec.remes.module.query.list;

import android.app.ProgressDialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.smec.moblie.R;
import com.smec.moblie.activity.ArrayListStock;
import com.smec.moblie.databinding.QueryListBinding;
import com.smec.remes.base.SmecBaseFragment;
import com.smec.remes.bean.query.MantrPrice;
import com.smec.remes.bean.query.Stock;
import com.smec.remes.module.query.SmecQueryPresenter;
import com.smec.remes.module.query.list.adapter.SmecListAdapter;
import com.smec.remes.util.CommonUtils;
import com.smec.remes.util.GetFullUrl;
import com.smec.remes.util.UserIdGet;
import com.smec.remes.util.WmsConstant;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Administrator on 2018/1/4.
 */

public class SmecListFragment extends SmecBaseFragment<SmecQueryPresenter> {

    private QueryListBinding queryListBinding;
    public static final String Price="MantrPrice";
    private String _url="QueryWmsStockServicePS";
    private String _PriceUrl="QueryProductPriceServicePS";
    private Gson gson = new Gson();
    private SmecListAdapter smecListAdapter;
    private int pageNumber=1;
    private String  status;
    private ProgressDialog progressDialog;
    private Boolean diaLog=false;
    private Boolean senior=false;
    private ArrayList<String> mantrPriceArrayList=new ArrayList<>();
    private ArrayList<Stock> arrayList=new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        queryListBinding=DataBindingUtil.inflate(inflater, R.layout.query_list,container,false);
        smecListAdapter=new SmecListAdapter(getActivity(),mRxBus);
        queryListBinding.listRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        queryListBinding.listRecyclerView.setAdapter(smecListAdapter);
        _Query();
        _load();
        return queryListBinding.getRoot();
    }

    /**
     *  上拉加载,下拉刷新
     */
    public void _load(){
        queryListBinding.ptr.setHeaderView(WmsConstant.getSinaRefreshView());
        queryListBinding.ptr.setBottomView(new LoadingView(getActivity()));
        queryListBinding.ptr.setAutoLoadMore(true);
        queryListBinding.ptr.setEnableOverScroll(false);
        queryListBinding.ptr.setEnableLoadmore(true);    //设置是否关闭上拉加载
        queryListBinding.ptr.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                pageNumber=1;
                status="onRefresh";
                smecListAdapter._clear();
                _getList();
                pageNumber+=1;
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                status="onLoadMore";
                _getList();
                pageNumber+=1;
            }
        });
    }

    /**
     *  搜索框
     * @return
     */
    public void _Query(){
        queryListBinding.ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryListBinding.edSearch.setText("");
            }
        });
        queryListBinding.edSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                queryListBinding.ivDelete.setVisibility(View.VISIBLE);
            }
        });
        queryListBinding.ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                senior=false;
                smecListAdapter._clear();
                arrayList.clear();
                mantrPriceArrayList.clear();
                queryListBinding.ptr.startRefresh();
                CommonUtils.hideImmManager(queryListBinding.getRoot());
                if(progressDialog == null){
                    progressDialog=new ProgressDialog(getActivity());
                }
                progressDialog.setMessage("正在查询.....");
                progressDialog.show();
                diaLog=true;
                queryListBinding.listRecyclerView.smoothScrollToPosition(0);
            }
        });
        queryListBinding.edSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    senior=false;
                    smecListAdapter._clear();
                    arrayList.clear();
                    mantrPriceArrayList.clear();
                    queryListBinding.ptr.startRefresh();
                    CommonUtils.hideImmManager(queryListBinding.getRoot());
                    if(progressDialog == null){
                        progressDialog=new ProgressDialog(getActivity());
                    }
                    progressDialog.setMessage("正在查询.....");
                    progressDialog.show();
                    diaLog=true;
                    queryListBinding.listRecyclerView.smoothScrollToPosition(0);
                }
                return false;
            }
        });

    }

    /**
     *  调接口，获取数据
     * @return
     */
    public void _getList(){
        Map<String, String> params = new HashMap<String, String>();
        if(senior){
            params.put("WarehouseNo", _getEd(queryListBinding.edWarehouse.getText().toString()));
            params.put("WarehouseName", _getEd(queryListBinding.edWarehouseName.getText().toString()));
            params.put("Matnr", _getEd(queryListBinding.edMantr.getText().toString()));
            params.put("MatnrName", _getEd(queryListBinding.edMantrName.getText().toString()));
        }else {
            params.put("Matnr", _getEd(queryListBinding.edSearch.getText().toString()));
        }
        params.put("UserName", UserIdGet._getId());
        params.put("PageSize", "5");
        params.put("PageNum", String.valueOf(pageNumber));
        String adress= GetFullUrl.getFullUrl(_url,params);
        String priceAdress=GetFullUrl.getFullUrl(_PriceUrl,params);
        Log.w("URL", GetFullUrl.getFullUrl(_url,params));
        OkHttpUtils.get().url(adress).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if(status.equals("onRefresh")){
                    queryListBinding.ptr.finishRefreshing();
                }else {
                    queryListBinding.ptr.finishLoadmore();
                }
                if(diaLog){
                    progressDialog.dismiss();
                    diaLog=false;
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if(diaLog){
                    progressDialog.dismiss();
                    diaLog=false;
                }
                if(status.equals("onRefresh")){
                    queryListBinding.ptr.finishRefreshing();
                }else {
                    queryListBinding.ptr.finishLoadmore();
                }
                ArrayListStock arrayListStock=gson.fromJson(response.toString().trim(),ArrayListStock.class);
                if(CommonUtils.notEmpty(arrayListStock.getStocks())){
                    for(int i=0;i<arrayListStock.getStocks().size();i++){
                        arrayList.add(arrayListStock.getStocks().get(i));
                        _getPrice(arrayListStock.getStocks().get(i).getMatnr(),i);
                    }
                }

                if(CommonUtils.notEmpty(arrayListStock.getStocks())){
                    mantrPriceArrayList.clear();
                    for (int i=0;i<arrayList.size();i++){
                        mantrPriceArrayList.add(arrayList.get(i).getPrice());
                    }
                    smecListAdapter.setArrayList(arrayList,status,mantrPriceArrayList);
                }
            }
        });
    }

    public String _getEd(String a){
        if(TextUtils.isEmpty(a)){
            return "";
        }else {
            return a;
        }
    }

    /**
     *  获取价格
     */
    public void _getPrice(final String mantr, final int i){
        Map<String, String> params = new HashMap<String, String>();
        params.put("arg0",mantr);
        String priceAdress=GetFullUrl.getFullUrl(_PriceUrl,params);
        OkHttpUtils.get().url(priceAdress).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                MantrPrice mantrPrice=gson.fromJson(response.toString(),MantrPrice.class);
                arrayList.get(i).setPrice(mantrPrice.getPrice());
            }
        });
    }

    public static SmecListFragment newInstance() {
        Bundle args = new Bundle();
        SmecListFragment fragment = new SmecListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected SmecQueryPresenter getPersenter() {
        return new SmecQueryPresenter(getContext());
    }
}
